<template>
  <div class="one">
    <h1>{{ id ? "编辑" : "新建" }}视频</h1>
    <!-- 在保存时，执行form的submit事件，native表示原生的表单，prevent表示阻止默认提交     -->
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" multiple>
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属英雄">
        <!-- filterable 可以筛选（可以动手搜索） -->
        <el-select clear filterable v-model="model.hero">
          <el-option
            v-for="hero in heroes"
            :key="hero._id"
            :label="hero.name"
            :value="hero._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="视频地址">
        <el-input v-model="model.address"></el-input>
      </el-form-item>
      <el-form-item label="视频图片">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="getAuthHeaders()"
          :show-file-list="false"
          :on-success="afterUpload"
        >
          <img v-if="model.image" :src="model.image" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    // 接收id
    id: {},
  },
  data() {
    return {
      model: {},
      categories: [],
      heroes: [],
    };
  },
  created() {
    this.id && this.fetch();
    this.fetchVideos();
    this.fetchHeroes();
  },
  methods: {
    // 上传图片成功之后的调用
    afterUpload(res) {
      // vue自带的显示赋值
      // this.model.icon = res.url
      this.$set(this.model, "image", res.url);
    },
    async save() {
      let res = []; // eslint-disable-line no-unused-vars
      if (this.id) {
        res = await this.$http.put(`rest/great_videos/${this.id}`, this.model);
      } else {
        res = await this.$http.post("rest/great_videos", this.model);
      }
      // 跳转到分类列表页
      this.$router.push("/great_videos/list");
      // 提示成功信息
      this.$message({
        type: "success",
        message: "保存成功",
      });
    },
    async fetch() {
      const res = await this.$http.get(`rest/great_videos/${this.id}`);
      this.model = res.data;
    },
    // 上级分类信息获取
    async fetchVideos() {
      const res = await this.$http.get(`rest/categories`);
      this.categories = res.data;
    },
    async fetchHeroes() {
      const res = await this.$http.get(`rest/heroes`);
      this.heroes = res.data;
    },
  },
};
</script>
